import logging

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QFormLayout, QLineEdit, QPushButton,
                             QLabel, QComboBox, QMessageBox, QHBoxLayout, QGroupBox,
                             QDoubleSpinBox, QFrame, QDialog, QGridLayout)
from PyQt5.QtGui import QFont, QColor, QPalette
from PyQt5.QtCore import Qt, QTimer
from bank_manage_system.user.client_operations import ClientOperations
import re

# 使用全局样式变量
PRIMARY_COLOR = "#3498db"  # 主题蓝色
SECONDARY_COLOR = "#2ecc71"  # 绿色
ACCENT_COLOR = "#6a5acd"  # 强调色
BG_COLOR = "#f8f9fa"  # 背景色
TEXT_COLOR = "#2c3e50"  # 文字颜色
WARNING_COLOR = "#e74c3c"  # 警告红色
GREEN_BG_COLOR = "#e8f5e9"  # 绿色背景色
BLUE_BG_COLOR = "#e3f2fd"  # 蓝色背景色

# 字体配置
HEADER_FONT = QFont("Microsoft YaHei UI", 12, QFont.Bold)
LABEL_FONT = QFont("Microsoft YaHei UI", 10)
BUTTON_FONT = QFont("Microsoft YaHei UI", 10, QFont.Bold)
INPUT_FONT = QFont("Microsoft YaHei UI", 10)
VALUE_FONT = QFont("Microsoft YaHei UI", 11, QFont.Bold)  # 数值字体加粗


class TransactionOperationsTab(QWidget):
    def __init__(self, db, card_id):
        super().__init__()
        self.db = db
        self.card_id = card_id
        self.client_ops = ClientOperations(db, card_id)
        self.initUI()
        self.apply_styles()
        # 确保在UI初始化完成后再刷新余额
        QTimer.singleShot(100, self.refresh_balance)

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        # 创建日志处理器
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def initUI(self):
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(15, 10, 15, 15)
        self.setContentsMargins(0, 0, 0, 0)  # 减少主窗口边距

        # ================= 顶部按钮布局 =================
        top_buttons_layout = QHBoxLayout()
        top_buttons_layout.setContentsMargins(0, 0, 0, 10)
        top_buttons_layout.setSpacing(10)

        # 刷新余额按钮
        refresh_btn = QPushButton("刷新余额")
        refresh_btn.setFont(BUTTON_FONT)
        refresh_btn.setMinimumHeight(40)
        refresh_btn.clicked.connect(self.refresh_balance)

        # 全部转出按钮
        self.transfer_all_btn = QPushButton("全部转出")
        self.transfer_all_btn.setFont(BUTTON_FONT)
        self.transfer_all_btn.setMinimumHeight(40)
        self.transfer_all_btn.setVisible(False)
        self.transfer_all_btn.clicked.connect(self.transfer_all_balance)

        top_buttons_layout.addWidget(refresh_btn)
        top_buttons_layout.addWidget(self.transfer_all_btn)
        top_buttons_layout.setStretch(0, 1)
        top_buttons_layout.setStretch(1, 1)

        main_layout.addLayout(top_buttons_layout)

        # ================= 账户信息卡片 =================
        account_group = QGroupBox()
        account_layout = QVBoxLayout(account_group)
        account_layout.setContentsMargins(0, 5, 0, 5)  # 减少边距

        # 创建一个网格布局来放置两个信息框
        info_grid = QGridLayout()
        info_grid.setSpacing(10)  # 框之间的间距

        # ================= 付款账户信息框 (长条形) =================
        payment_frame = QFrame()
        payment_frame.setObjectName("paymentFrame")
        payment_layout = QHBoxLayout(payment_frame)
        payment_layout.setContentsMargins(15, 10, 15, 10)  # 增加内边距

        # 添加左侧标题标签
        payment_label = QLabel("付款账户:")
        payment_label.setFont(LABEL_FONT)
        payment_layout.addWidget(payment_label)

        # 添加付款账户值 (掩码显示)
        masked_card_id = f"{self.card_id[:6]} ***** {self.card_id[-4:]}"
        self.card_id_label = QLabel(masked_card_id)
        self.card_id_label.setFont(VALUE_FONT)
        payment_layout.addWidget(self.card_id_label)

        # 添加弹性空间使内容左对齐
        payment_layout.addStretch(1)

        info_grid.addWidget(payment_frame, 0, 0)  # 添加到网格第一行

        # ================= 可用余额信息框 (长条形) =================
        balance_frame = QFrame()
        balance_frame.setObjectName("balanceFrame")
        balance_layout = QHBoxLayout(balance_frame)
        balance_layout.setContentsMargins(15, 10, 15, 10)

        # 添加左侧标题标签
        balance_label = QLabel("可用余额:")
        balance_label.setFont(LABEL_FONT)
        balance_layout.addWidget(balance_label)

        # 添加余额值
        self.balance_value = QLabel("¥0.00")
        self.balance_value.setFont(VALUE_FONT)
        self.balance_value.setStyleSheet(f"color: {SECONDARY_COLOR};")  # 设置绿色文本
        balance_layout.addWidget(self.balance_value)

        # 添加弹性空间使内容左对齐
        balance_layout.addStretch(1)

        info_grid.addWidget(balance_frame, 1, 0)  # 添加到网格第二行

        account_layout.addLayout(info_grid)  # 将网格添加到账户组
        main_layout.addWidget(account_group)

        # ================= 交易操作面板 =================
        operation_group = QGroupBox("交易操作")
        operation_layout = QFormLayout(operation_group)
        operation_layout.setVerticalSpacing(15)
        operation_layout.setContentsMargins(15, 15, 15, 15)
        operation_layout.setLabelAlignment(Qt.AlignRight)

        # 操作类型选择 - 垂直布局
        type_layout = QVBoxLayout()
        type_label = QLabel("交易类型:")
        type_label.setFont(LABEL_FONT)
        type_layout.addWidget(type_label)

        self.operation_type = QComboBox()
        self.operation_type.addItems(["存款", "取款", "转账"])
        self.operation_type.setFont(INPUT_FONT)
        self.operation_type.currentTextChanged.connect(self.update_form)
        type_layout.addWidget(self.operation_type)
        operation_layout.addRow(type_layout)

        # 币种选择 (仅显示人民币)
        currency_layout = QVBoxLayout()
        currency_label = QLabel("币种")
        currency_label.setFont(LABEL_FONT)

        currency_value = QLabel("人民币元")
        currency_value.setFont(INPUT_FONT)
        currency_value.setStyleSheet(
            f"color: {TEXT_COLOR}; border: 1px solid #e0e0e0; padding: 8px; border-radius: 4px;")

        currency_layout.addWidget(currency_label)
        currency_layout.addWidget(currency_value)
        operation_layout.addRow(currency_layout)

        # 金额输入
        amount_layout = QVBoxLayout()
        amount_label = QLabel("交易金额")
        amount_label.setFont(LABEL_FONT)
        amount_layout.addWidget(amount_label)

        # 金额输入框布局
        amount_input_layout = QHBoxLayout()
        amount_input_layout.setSpacing(0)

        # 增加"¥"前缀符号
        currency_symbol = QLabel("¥")
        currency_symbol.setFont(QFont("Microsoft YaHei UI", 12, QFont.Bold))
        currency_symbol.setStyleSheet(f"color: {TEXT_COLOR}; padding: 5px;")
        currency_symbol.setMinimumWidth(30)
        currency_symbol.setAlignment(Qt.AlignCenter)
        amount_input_layout.addWidget(currency_symbol)

        # 金额输入框
        self.amount_input = QDoubleSpinBox()
        self.amount_input.setFont(INPUT_FONT)
        self.amount_input.setDecimals(2)
        self.amount_input.setMinimum(0.01)
        self.amount_input.setMaximum(99999999.99)
        self.amount_input.setValue(1000.00)
        self.amount_input.setButtonSymbols(QDoubleSpinBox.NoButtons)
        self.amount_input.setStyleSheet(f"""
            QDoubleSpinBox {{
                border: 1px solid #e0e0e0;
                border-left: none;
                border-top-right-radius: 4px;
                border-bottom-right-radius: 4px;
                padding: 8px 12px;
                min-height: 30px;
                font-size: 11pt;
                background-color: white;
            }}
        """)
        amount_input_layout.addWidget(self.amount_input)
        amount_layout.addLayout(amount_input_layout)

        # 快速金额按钮布局
        quick_amount_layout = QHBoxLayout()
        quick_amount_layout.setSpacing(5)

        yuan_btn = QPushButton("百")
        yuan_btn.setFont(INPUT_FONT)
        yuan_btn.setMinimumHeight(30)
        yuan_btn.clicked.connect(lambda: self.quick_amount(100))

        jiao_btn = QPushButton("十")
        jiao_btn.setFont(INPUT_FONT)
        jiao_btn.setMinimumHeight(30)
        jiao_btn.clicked.connect(lambda: self.quick_amount(10))

        fen_btn = QPushButton("元")
        fen_btn.setFont(INPUT_FONT)
        fen_btn.setMinimumHeight(30)
        fen_btn.clicked.connect(lambda: self.quick_amount(1))

        quick_amount_layout.addWidget(yuan_btn)
        quick_amount_layout.addWidget(jiao_btn)
        quick_amount_layout.addWidget(fen_btn)

        # 设置快速按钮宽度均等
        for i in range(quick_amount_layout.count()):
            item = quick_amount_layout.itemAt(i).widget()
            item.setMinimumWidth(50)
            item.setMaximumWidth(100)

        amount_layout.addLayout(quick_amount_layout)
        operation_layout.addRow(amount_layout)

        # 收款账户部分 (仅转账时显示)
        self.recipient_container = QWidget()
        recipient_layout = QFormLayout(self.recipient_container)
        recipient_layout.setSpacing(10)
        recipient_layout.setContentsMargins(0, 10, 0, 10)

        # 收款账户信息标签
        recipient_label = QLabel("收款账户信息")
        recipient_label.setFont(LABEL_FONT)
        recipient_layout.addRow(recipient_label)

        # 收款人名称输入
        name_label = QLabel("收款人名称:")
        name_label.setFont(LABEL_FONT)
        self.target_name_input = QLineEdit()
        self.target_name_input.setPlaceholderText("请输入完整名称")
        self.target_name_input.setFont(INPUT_FONT)
        recipient_layout.addRow(name_label, self.target_name_input)

        # 收款账号输入
        account_label = QLabel("收款账号:")
        account_label.setFont(LABEL_FONT)
        self.target_card_input = QLineEdit()
        self.target_card_input.setPlaceholderText("请输入账号")
        self.target_card_input.setFont(INPUT_FONT)
        recipient_layout.addRow(account_label, self.target_card_input)

        # 附言输入
        comment_label = QLabel("附言 (非必填):")
        comment_label.setFont(LABEL_FONT)
        self.comment_input = QLineEdit()
        self.comment_input.setPlaceholderText("转账说明")
        self.comment_input.setFont(INPUT_FONT)
        recipient_layout.addRow(comment_label, self.comment_input)

        operation_layout.addRow(self.recipient_container)
        self.recipient_container.setVisible(False)  # 初始隐藏

        # 安全提示区域
        self.tips_frame = QFrame()
        tips_layout = QVBoxLayout(self.tips_frame)
        tips_layout.setContentsMargins(10, 5, 10, 5)
        tips_layout.setSpacing(3)

        tip1 = QLabel("• 为了您的资金安全，请核实收款人身份")
        tip1.setFont(QFont("Microsoft YaHei UI", 9))

        tip2 = QLabel("• 跨行转账到账时间以收款银行处理为准")
        tip2.setFont(QFont("Microsoft YaHei UI", 9))

        tips_layout.addWidget(tip1)
        tips_layout.addWidget(tip2)
        self.tips_frame.setVisible(False)  # 初始隐藏

        operation_layout.addRow(self.tips_frame)

        main_layout.addWidget(operation_group)

        # ================= 下一步/执行操作按钮 =================
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 5)

        # 添加左侧弹性空间使按钮右对齐
        button_layout.addStretch(1)

        # 下一步/执行操作按钮
        self.next_btn = QPushButton("下一步")
        self.next_btn.setFont(BUTTON_FONT)
        self.next_btn.setMinimumHeight(40)
        self.next_btn.setMinimumWidth(120)
        self.next_btn.clicked.connect(self.execute_operation)
        button_layout.addWidget(self.next_btn)

        main_layout.addLayout(button_layout)

        self.setLayout(main_layout)

    def apply_styles(self):
        """应用样式表 - 优化按钮样式和布局"""
        # 主样式
        self.setStyleSheet(f"""
            QWidget {{
                background-color: {BG_COLOR};
            }}

            QGroupBox {{
                border: 1px solid #ddd;
                border-radius: 8px;
                margin-top: 5px;
                padding-top: 10px;
                background-color: white;
            }}

            QGroupBox::title {{
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0px 10px;
                background-color: transparent;
                font-weight: bold;
                color: {TEXT_COLOR};
                font-size: 11pt;
            }}

                #paymentFrame {{
                background-color: #e0f0ff;  /* 浅蓝色背景 */
                border:none;
                border-radius: 15px;        /* 椭圆效果的关键 */
                padding: 12px 20px;         /* 增加内边距使文字更居中 */
                font-family: 'Microsoft YaHei UI';
            }}
            
            /* 付款账户标签样式 */
            #paymentFrame QLabel {{
                font-weight: bold;          /* 加粗文字 */
                font-size: 11pt;            /* 字体大小 */
                text-align: center;          /* 文字居中 */
            }}
            
            /* ================= 可用余额信息框 - 椭圆一体效果 ================= */
            #balanceFrame {{
                background-color: #e0f8f0;  /* 浅绿色背景 */
                border: none;
                border-radius: 15px;        /* 椭圆效果 */
                padding: 12px 20px;
            }}
            
            /* 可用余额标签样式 */
            #balanceFrame QLabel {{
                font-weight: bold;
                font-size: 11pt;
                text-align: center;
            }}

            QLabel {{
                color: {TEXT_COLOR};
            }}

            QComboBox {{
                background-color: white;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                padding: 8px 12px;
                min-height: 30px;
                font-size: 11pt;
            }}

            QLineEdit {{
                background-color: white;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                padding: 8px 12px;
                min-height: 30px;
                font-size: 11pt;
            }}

            QPushButton {{
                border-radius: 4px;
                padding: 8px 12px;
                font-weight: bold;
                font-size: 10pt;
                min-height: 30px;
            }}

            QPushButton#nextBtn {{
                background-color: {PRIMARY_COLOR};
                color: white;
            }}

            QPushButton#nextBtn:hover {{
                background-color: #2980b9;
            }}

            /* 顶部按钮样式 */
            QPushButton#refreshBtn {{
                background-color: #f0f0f0;
                color: #333;
                border: 1px solid #ccc;
            }}

            QPushButton#refreshBtn:hover {{
                 background-color: {PRIMARY_COLOR};
                color: white;
            }}

            QPushButton#transferAllBtn {{
                background-color: {PRIMARY_COLOR};
                color: white;
                border: 1px solid {PRIMARY_COLOR};
            }}

            QPushButton#transferAllBtn:hover {{
                background-color: #2980b9;
            }}

            /* 快速金额按钮 */
            QPushButton#quickAmountBtn {{
                background-color: {PRIMARY_COLOR};
                border: 1px solid #ddd;
                font-size: 10pt;
                min-height: 30px;
            }}

            QPushButton#quickAmountBtn:hover {{
                background-color: #e0e0e0;
            }}

            QDoubleSpinBox {{
                border: 1px solid #e0e0e0;
                border-left: none;
                border-top-right-radius: 4px;
                border-bottom-right-radius: 4px;
                padding: 8px 12px;
                min-height: 30px;
                font-size: 11pt;
                background-color: white;
            }}
        """)

        # 单独为按钮设置对象名以便应用特定样式
        self.transfer_all_btn.setObjectName("transferAllBtn")
        self.next_btn.setObjectName("nextBtn")

        # 设置刷新按钮的样式（在代码中获取刷新按钮）
        for i in range(self.layout().count()):
            layout = self.layout().itemAt(i)
            if isinstance(layout, QHBoxLayout) and layout.itemAt(0) and layout.itemAt(0).widget():
                widget = layout.itemAt(0).widget()
                if isinstance(widget, QPushButton) and widget.text() == "刷新余额":
                    widget.setObjectName("refreshBtn")

        # 设置快速金额按钮的样式
        self.findChildren(QPushButton, options=Qt.FindDirectChildrenOnly)
        for btn in self.findChildren(QPushButton):
            if btn.text() in ["百", "十", "元"]:
                btn.setObjectName("quickAmountBtn")

    def transfer_all_balance(self):
        """全部转出功能实现"""
        try:
            # 获取当前余额（移除货币符号和逗号）
            balance_text = self.balance_value.text().replace("¥", "").replace(",", "")
            balance = float(balance_text)

            # 设置转账金额
            self.amount_input.setValue(balance)

            # 如果当前不是转账类型，则切换到转账类型
            if self.operation_type.currentText() != "转账":
                self.operation_type.setCurrentText("转账")

            QMessageBox.information(
                self,
                "操作提示",
                f"已设置转账金额为账户当前余额: ¥{balance:.2f}",
                QMessageBox.Ok
            )

        except Exception as e:
            self.logger.error(f"全部转出失败: {str(e)}")
            QMessageBox.warning(
                self,
                "操作失败",
                f"无法获取账户余额: {str(e)}",
                QMessageBox.Ok
            )

    def update_form(self, operation):
        """根据操作类型更新表单"""
        if operation == "转账":
            self.recipient_container.setVisible(True)
            self.tips_frame.setVisible(True)
            self.transfer_all_btn.setVisible(True)
            self.next_btn.setText("下一步")
        else:
            self.recipient_container.setVisible(False)
            self.tips_frame.setVisible(False)
            self.transfer_all_btn.setVisible(False)
            self.next_btn.setText("执行操作")

            # 对于取款操作，设置默认金额
            if operation == "取款":
                self.amount_input.setValue(1000.00)

    def refresh_balance(self):
        """刷新余额显示 """
        try:
            query = "SELECT balance FROM cardinfo WHERE cardID = %s"
            result = self.db.execute_query(query, (self.card_id,))

            if result and result[0]:
                balance = float(result[0].get('balance', 0.0))
                self.balance_value.setText(f"¥{balance:,.2f}")
            else:
                self.balance_value.setText("¥0.00")
                self.logger.error("无法获取账户余额")
        except Exception as e:
            self.logger.error(f"刷新余额失败: {str(e)}")
            self.balance_value.setText("¥0.00")

    def validate_input(self):
        """验证用户输入 """
        operation = self.operation_type.currentText()
        amount = self.amount_input.value()

        # 验证金额
        if amount <= 0:
            QMessageBox.warning(self, "输入错误", "金额必须大于0")
            return False

        # 检查可用余额是否充足（仅对取款和转账）
        if operation in ["取款", "转账"]:
            current_balance = float(self.balance_value.text().replace("¥", "").replace(",", ""))
            if amount > current_balance:
                QMessageBox.warning(self, "余额不足", "账户余额不足，无法完成此操作")
                return False

        # 验证转账相关信息
        if operation == "转账":
            # 收款账号验证
            target_card = self.target_card_input.text().strip()
            if not target_card:
                QMessageBox.warning(self, "输入错误", "请输入收款账号")
                return False

            # 验证卡号格式
            if not re.match(r'^\d{16,19}$', target_card):
                QMessageBox.warning(self, "账号格式错误", "账号应为16-19位数字")
                return False

            # 检查是否是同一张卡
            if target_card == self.card_id:
                QMessageBox.warning(self, "操作错误", "不能转账给自己")
                return False

            # 收款人名称验证
            target_name = self.target_name_input.text().strip()
            if not target_name:
                QMessageBox.warning(self, "输入错误", "请输入收款人名称")
                return False

        return True

    def execute_operation(self):
        """执行交易操作"""
        operation = self.operation_type.currentText()

        # 对于转账操作，只显示确认页面，不直接执行
        if operation == "转账":
            self.show_confirmation_dialog()
            return

        # 验证输入
        if not self.validate_input():
            return

        amount = self.amount_input.value()
        comment = self.comment_input.text().strip() if operation == "转账" else ""
        target_card = self.target_card_input.text().strip() if operation == "转账" else ""

        # 操作确认
        confirm_msg = f"确认{operation}¥{amount:,.2f}吗？"
        if operation == "转账":
            confirm_msg += f"\n收款账户: {target_card}"

        reply = QMessageBox.question(
            self, '确认操作', confirm_msg,
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply != QMessageBox.Yes:
            return

        # 执行操作
        if operation == "存款":
            result = self.client_ops.deposit(amount)
        elif operation == "取款":
            result = self.client_ops.withdraw(amount)
        else:  # 转账
            result = self.client_ops.transfer(target_card, amount)

        # 显示结果
        if result.get('success', False):
            QMessageBox.information(
                self,
                f"{operation}成功",
                f"¥{amount:,.2f}{operation}操作已完成",
                QMessageBox.Ok
            )
            # 刷新余额
            self.refresh_balance()
            # 清空输入
            self.amount_input.setValue(1000.00)
            self.comment_input.clear()
        else:
            error_msg = result.get('message', '操作失败，未知错误')
            QMessageBox.warning(
                self,
                "操作失败",
                error_msg,
                QMessageBox.Ok
            )

    def show_confirmation_dialog(self):
        """显示转账确认对话框"""
        # 验证输入
        if not self.validate_input():
            return

        amount = self.amount_input.value()
        target_card = self.target_card_input.text().strip()
        target_name = self.target_name_input.text().strip()
        comment = self.comment_input.text().strip()

        # 创建确认对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("确认转账信息")
        dialog.setFixedSize(800, 600)
        dialog_layout = QVBoxLayout(dialog)
        dialog_layout.setContentsMargins(30, 20, 30, 20)
        dialog_layout.setSpacing(15)

        # 标题
        title_label = QLabel("请确认转账信息")
        title_label.setFont(HEADER_FONT)
        title_label.setAlignment(Qt.AlignCenter)
        dialog_layout.addWidget(title_label)

        # 信息卡片
        info_frame = QFrame()
        info_frame.setObjectName("infoFrame")
        info_frame.setStyleSheet("background-color: #f9f9f9; border-radius: 8px; padding: 15px;")
        info_layout = QFormLayout(info_frame)
        info_layout.setLabelAlignment(Qt.AlignRight)
        info_layout.setVerticalSpacing(12)

        # 添加转账信息
        info_layout.addRow("付款账户:", QLabel(f"{self.card_id[:6]} ***** {self.card_id[-4:]}"))
        info_layout.addRow("收款账户:", QLabel(target_card))
        info_layout.addRow("收款人:", QLabel(target_name))
        info_layout.addRow("转账金额:", QLabel(f"¥{amount:,.2f}"))
        info_layout.addRow("备注:", QLabel(comment))

        dialog_layout.addWidget(info_frame)

        # 安全提醒
        reminder_label = QLabel("温馨提示：请确认转账信息是否正确，转账操作一旦完成无法撤销")
        reminder_label.setFont(QFont("Microsoft YaHei UI", 9))
        reminder_label.setStyleSheet(f"color: {WARNING_COLOR};")
        reminder_label.setAlignment(Qt.AlignCenter)
        dialog_layout.addWidget(reminder_label)

        # 按钮布局
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(15)
        btn_layout.setContentsMargins(20, 0, 20, 0)  # 增加边距

        cancel_btn = QPushButton("取消")
        cancel_btn.setFixedSize(120, 45)  # 固定尺寸
        cancel_btn.setStyleSheet("background-color: #f1f1f1; color: #333;")
        cancel_btn.clicked.connect(dialog.reject)

        confirm_btn = QPushButton("确认转账")
        confirm_btn.setFixedSize(180, 45)
        confirm_btn.setStyleSheet(f"background-color: {PRIMARY_COLOR}; color: white;")
        confirm_btn.clicked.connect(lambda: self.execute_transfer(dialog, target_card, amount))

        btn_layout.addStretch(1)
        btn_layout.addWidget(cancel_btn)
        btn_layout.addWidget(confirm_btn)
        btn_layout.addStretch(1)

        dialog_layout.addLayout(btn_layout)

        dialog.exec_()

    def execute_transfer(self, dialog, target_card, amount):
        """执行转账操作"""
        # 实际执行转账
        result = self.client_ops.transfer(target_card, amount)

        if result.get('success', False):
            QMessageBox.information(
                dialog,
                "转账成功",
                f"¥{amount:,.2f}已成功转账至账户\n{target_card}",
                QMessageBox.Ok
            )
            dialog.accept()
            # 刷新余额
            self.refresh_balance()
            # 清空输入
            self.amount_input.setValue(1000.00)
            self.target_card_input.clear()
            self.target_name_input.clear()
            self.comment_input.clear()
        else:
            error_msg = result.get('message', '转账失败，请重试')
            QMessageBox.warning(
                dialog,
                "转账失败",
                error_msg,
                QMessageBox.Ok
            )

    def quick_amount(self, multiplier):
        """快速设置金额按钮"""
        current_value = self.amount_input.value()
        self.amount_input.setValue(current_value + multiplier)